#ifndef _TG_BUFFERBLOCK_H_
#define _TG_BUFFERBLOCK_H_

#include "stdio.h"
#include "memory.h"
#include "malloc.h"
#include "TG_Type.h"

#define DKQ_ALIGNED_MALLOC 

typedef struct _tagTGBufferBlock
{
	UINT8 *pBuffer;
	UINT32 nLength;
	UINT32 nCapacity;
	UINT32 nOffset1,nOffset2;

	_tagTGBufferBlock()
	{
		memset(this,0,sizeof(*this));
	}

	~_tagTGBufferBlock()
	{
		Release();
	}

	void Release()
	{
		if( NULL != pBuffer )
		{
#ifdef DKQ_ALIGNED_MALLOC
			_aligned_free(pBuffer);
#else
			delete[]pBuffer;
#endif
			pBuffer = NULL;
		}
		nLength   = 0;
		nCapacity = 0;
	}

	BOOL Allocate(UINT32 nNewSize)
	{
		if( nNewSize > nCapacity )
		{
			if( NULL != pBuffer )
			{
#ifdef DKQ_ALIGNED_MALLOC
				_aligned_free(pBuffer);
#else
				delete[]pBuffer;
#endif
				pBuffer = NULL;
			}

			nNewSize += 100;
#ifdef DKQ_ALIGNED_MALLOC
			pBuffer = (UINT8 *)_aligned_malloc(nNewSize, 16);
#else
			pBuffer = new UINT8[nNewSize];
#endif		
			if( NULL == pBuffer )
			{
				return FALSE;
			}

			nCapacity = nNewSize;
			
			memset(pBuffer,0,nCapacity);
		}

		nLength = 0;
		if( NULL != pBuffer )
		{
			return TRUE;
		}

		return FALSE;
	}

	BOOL Enlarge(UINT32 nNewSize)
	{
		if( nNewSize > nCapacity )
		{
			nNewSize += 100;
#ifdef DKQ_ALIGNED_MALLOC
			UINT8 *pNewBuffer = (UINT8 *)_aligned_malloc(nNewSize, 16);
#else
			UINT8 *pNewBuffer = new UINT8[nNewSize];
#endif		
			if( NULL == pNewBuffer )
			{
				return FALSE;
			}
			memset(pNewBuffer,0,nNewSize);

			if( NULL != pBuffer )
			{
				if( nLength > 0 )
				{
					memcpy(pNewBuffer,pBuffer,nLength);
				}
#ifdef DKQ_ALIGNED_MALLOC
				_aligned_free(pBuffer);
#else
				delete[]pBuffer;
#endif
			}

			nCapacity = nNewSize;
			pBuffer   = pNewBuffer;
		}

		if( NULL != pBuffer )
		{
			return TRUE;
		}

		return FALSE;
	}

	BOOL Resize(UINT32 nSize)
	{
		if( NULL != pBuffer )
		{
#ifdef DKQ_ALIGNED_MALLOC
			_aligned_free(pBuffer);
#else
			delete[]pBuffer;
#endif
			pBuffer = NULL;
		}
		nLength   = 0;
		nCapacity = 0;

		nSize += 100;

#ifdef DKQ_ALIGNED_MALLOC
		pBuffer = (UINT8 *)_aligned_malloc(nSize, 16);
#else
		pBuffer = new UINT8[nSize];
#endif	
		if( NULL == pBuffer )
		{
			return FALSE;
		}
		nCapacity = nSize;
		memset(pBuffer,0,nSize);

		return TRUE;
	}

	void MemSet()
	{
		nLength   = 0;
		if( NULL != pBuffer )
		{
			memset(pBuffer,0,nCapacity);
		}
	}
	void MemSetPart(UINT32 nPos,UINT32 nSize)
	{
		if( NULL != pBuffer && 
			(nPos + nSize) <= nCapacity )
		{
			memset(pBuffer+nPos,0,nSize);
		}
	}

}TGBufferBlock;


#endif